package org.vison.wonfu.framework.soa.spi;

import com.ecwid.consul.v1.ConsulClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.vison.wonfu.framework.commons.Constants;
import org.vison.wonfu.framework.config.utils.MultiLevelConfigProvider;
import org.vison.wonfu.framework.soa.discovery.AutoServiceRegistration;
import org.vison.wonfu.framework.soa.discovery.ConsulServiceDiscovery;
import org.vison.wonfu.framework.soa.discovery.ServiceRegistryDiscovery;
import org.vison.wonfu.framework.soa.governance.GovernanceReporter;

@Configuration
public class SoaAutoConfigure {

    @Bean
    public SoaRefAnnotationPostProcessor soaRefBeanPostProcessor() {
        return new SoaRefAnnotationPostProcessor();
    }


    @Primary
    @Bean(name = Constants.CONSUL_SERVICE_REGISTRY_BEAN)
    public ServiceRegistryDiscovery serviceDiscovery(@Qualifier(Constants.GOVERNANCE_BEAN)
                                                         MultiLevelConfigProvider governanceMultiLevelConfigProvider,ConsulClient consulClient) {
        ServiceRegistryDiscovery serviceDiscovery =  new ConsulServiceDiscovery(governanceMultiLevelConfigProvider,consulClient);
//        serviceDiscovery.init();
        return serviceDiscovery;
    }

    @Bean
    public ConsulClient consulClient(@Qualifier(Constants.GOVERNANCE_BEAN) MultiLevelConfigProvider governanceMultiLevelConfigProvider) {
        return new ConsulClient(governanceMultiLevelConfigProvider.getString(Constants.CONSUL_HOST), governanceMultiLevelConfigProvider.getInteger(Constants.CONSUL_PORT));
    }

    @Bean
    public SoaServiceScanner soaServiceScanner(Environment environment) {
        return new SoaServiceScanner(environment);
    }

    @Bean
    public GovernanceReporter governanceReporter() {
        return new GovernanceReporter();
    }

    @Bean
    public AutoServiceRegistration autoServiceRegistration(ServiceRegistryDiscovery serviceRegistryDiscovery, MultiLevelConfigProvider defaultMultiLevelConfigProvider,
                                                           ServerProperties serverProperties) {
        return new AutoServiceRegistration(serviceRegistryDiscovery, defaultMultiLevelConfigProvider,serverProperties);
    }


}
